/**
 * 2017年3月8日
 * 二人牛牛
 * 玩家信息管理 当做大厅来用，不再多一层大厅
 */

var pomelo = require('pomelo');

var log = console.log;

var consts = require('./consts');

var userDao = require('../../dao/userDao');
var client = pomelo.app.get('redisUser');

var playerUtil = require('../util/player');
var utils = require('../../util/utils');

function PlayerManager() {
    this.id = 1;
    this.gameId = 5;

    this.playerData = {};
    this.playerNum = 0;
    this.roomData = {};
    this.channelService = pomelo.app.get('channelService');
    this.createChannel();

    this.roomPlayerCount = {};
}

var pro = PlayerManager.prototype;

pro.createChannel = function () {
    if (this.channel) {
        return this.channel;
    }
    var channelName = 'lobby_' + this.id;
    this.channel = this.channelService.getChannel(channelName, true);

    return this.channel;
};

/**
 * 2017年3月15日
 * 用户管理添加用户
 */
pro.addPlayer = function (msg, callback) {
    console.log('用户进入游戏 PlayerManage.addPlayer', JSON.stringify(msg));
    var self = this;
    var playerId = msg.playerId;

    var players = this.playerData;
    var player = {};

    // 如果还没有下线成功，那么就不让上线
    if (players[playerId]) {
        return callback('player ' + playerId + ' have not logout from game!');
    }

    playerUtil.playerLogin(msg, function (err, rel) {
        if (err) {
            console.log(err);
            callback(err);
        }
        else {
            player = rel;
            player.serverId = msg.serverId;
            players[playerId] = player;
            player.isRobot = false;

            self.playerNum++;

            self.channel.add(msg.playerId, msg.serverId);

            log('推送 onGameEnter!', self.getPlayerData(playerId));
            self.channel.pushMessage('onGameEnter', self.getPlayerData(playerId), null);

            var ret = { playerId };
            ret.gameId = self.gameId;
            ret.playerData = self.getPlayerData(playerId);
            ret.playerList = self.getPlayerList();
            ret.roomData = self.getRoomData();
            // log(ret);

            callback(null, ret);
        }
    });
};

// 获取当前用户名单
pro.getPlayerList = function () {
    log('获取当前用户名单!');
    var self = this;
    var playerList = [];
    var player;

    for (var playerId in this.playerData) {
        player = this.playerData[playerId];
        playerList.push({
            playerId: player.playerId,
            playerName: player.playerName,
            coin: player.coin
        });
    }
    return playerList;
};

// 获取当前用户信息
pro.getPlayerData = function (playerId) {
    log('获取当前用户信息： ', playerId);

    var playerData = {}, player;

    if (this.playerData[playerId]) {
        player = this.playerData[playerId];
        playerData = {
            playerId,
            playerName: player.playerName,
            coin: player.coin,
            score: player.score,
            roundCount: player.roundCount
        };
    }
    return playerData;
};

// 获取房间用户信息
pro.getRoomData = function () {
    return this.roomData;
};

// 把用户添加到房间信息中
// TODO: 只有用户是加入游戏的时候，才会发用户进入房间的广播，旁观不发广播
// 旁观也需要检查用户是否已经在房间中
// 需要返回房间已存在的用户列表
pro.addPlayerToRoom = function (playerId, rid, coin, players, cb) {
    log('添加用户到大厅的房间信息中');
    var type = consts.PLAYER.TYPE.PLAYER; // 玩家
    var sid = this.getSid(playerId);
    log('sid', sid);
    var backendSessionService = pomelo.app.get('backendSessionService');
    backendSessionService.getByUid(sid, playerId, function (err, bSession) {
        console.log(Array.isArray(bSession), bSession);
        log('获取到了后端服务器session');
        backendSession = bSession[0];
        backendSession.set('roomId', rid);
        backendSession.push('roomId', function () {
            log('把roomId push到了前端服务器！');
        });
    });

    // session.set('roomId', this.roomId);
    // session.push('roomId', function () {
    //     log('把roomId push到了前端服务器！');
    // });

    if (!this.roomData[playerId]) {
        this.roomData[playerId] = { playerId, rid, coin, type };

        if (!this.roomPlayerCount[rid]) {
            this.roomPlayerCount[rid] = 1;
        }
        else {
            this.roomPlayerCount[rid]++;
        }

        this.channel.pushMessage('onPlayerEnterRoom', this.roomData[playerId], null);
    }
    cb(null, players);
};

// 从房间中删除用户
pro.kickPlayerFromRoom = function (playerId, cb) {
    log('playerManager.delPlayerFromRoom 从房间中删除用户', playerId);
    var rid;
    if (this.roomData[playerId]) {
        rid = this.getRid(playerId);
        this.channel.pushMessage('onPlayerLeaveRoom', { playerId, rid }, null);

        if (this.roomData[playerId].type === consts.PLAYER.TYPE.PLAYER) {
            this.roomPlayerCount[rid]--;
        }

        delete this.roomData[playerId];
        cb(null);
    }
    else {
        cb('player: ' + playerId + 'not exists in roomData!');
    }
};

// 获取才只有一个人的房间号
pro.getWaitRoom = function () {
    log('获取才只有一个人的房间号');

    var rid;

    // 如果找到只有一个玩家的房间，就返回这个房间
    for (let i = 1; i <= 60; i++) {
        if (!this.roomPlayerCount[i]) {
            this.roomPlayerCount[i] = 0;
        }
        if (this.roomPlayerCount[i] === 1) {
            rid = i;
            break;
        }
    }
    if (!rid) {
        // 否则就返回第一个空房间
        for (let i = 1; i <= 60; i++) {
            if (this.roomPlayerCount[i] === 0) {
                rid = i;
                break;
            }
        }
    }

    return rid;
};

// 检查用户是否已经登录
pro.checkPlayerLogin = function (playerId) {
    log('检查用户是否已经登录');
    if (this.playerData[playerId]) {
        return true;
    }
    return false;
};

// 检查用户是否在房间中
pro.checkPlayerInRoom = function (playerId) {
    log('检查用户是否在房间中');
    if (this.roomData[playerId]) {
        return true;
    }
    return false;
};

// 检查用户是否在某个房间内
pro.checkPlayerRoom = function (playerId, rid) {
    log('检查用户是否在特定房间内！playerId: ', playerId, '、 rid: ', rid);

    if (this.roomData[playerId] && this.roomData[playerId].rid === rid) {
        return true;
    }
    return false;
};

// 用户离开游戏
pro.kickPlayer = function (playerId) {
    log('用户离开游戏. %s', playerId);

    var serverId = this.getSid(playerId);

    this.channel.leave(playerId, serverId);
    this.channel.pushMessage('onPlayerLeave', { playerId }, null);
    delete this.playerData[playerId];

    var key = 'onlineGameUser';
    client.hdel(key, playerId, function (err, rel) {
        if (err) {
            log(err);
            throw new Error('redis err:', err);
        }
        else {
            log('玩家 %s 已经退出游戏二人牛牛！', playerId);
        }
    })
};

// 获取用户的前端 Server Id
pro.getSid = function (playerId) {
    return this.playerData[playerId].serverId;
};

// 获取用户的房间号
pro.getRid = function (playerId) {
    return this.roomData[playerId].rid;
};

// 房间添加观察者
// 不用发广播
pro.addObserver = function (msg, cb) {
    var playerId = msg.playerId, rid = msg.rid, coin = msg.coin;
    var type = consts.PLAYER.TYPE.OBSERVER;

    this.roomData[playerId] = { playerId, rid, coin, type };
    cb(null, this.roomData);
};

// 房间用户准备
pro.gameReady = function (msg, cb) {
    log('房间用户准备！ playerManager.gameReady');

    var playerId = msg.playerId, rid = msg.rid;

    this.roomData[playerId].prepare = 1;
    this.channel.pushMessage('onRoomReady', { playerId, rid }, null);

    cb(null);
};

// 为大厅用户广播房间结算信息
pro.pushCalcResult = function (ret) {
    log('广播房间用户信息');

    // 同步roomData 中的用户金钱信息
    for (playerId in ret) {
        this.roomData[playerId].coin = ret[playerId].coin;
    }

    this.channel.pushMessage('onRoomCalc', ret, null);
};

/**
 * Expose 'playerManager' constructor.
 */
module.exports = PlayerManager;
